package campus.controller;

import campus.model.Menu;
import campus.model.User;
import campus.model.UserExample;
import campus.service.UserService;
import campus.util.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.*;

import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.util.List;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author VULCAN
 * @create 2020-05-06 22:26
 * @desc 用户
 **/
@RestController
@CrossOrigin
public class UserController  {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("admin")
    public List<User> selectByExample(UserExample example) {
        return userService.selectByExample(null);
    }
    /**
     * @name  菜单
     * @Author VULCAN
     * @Date 2020/5/6 23:40
     */
    @RequestMapping(value = "menu/{id}",method = RequestMethod.GET)
    public List<Menu> findMenu(@PathVariable(value = "id") String id) {
        return userService.findMenu(id);
    }
    /**
     * @name  登录
     * @Author VULCAN
     * @Date 2020/5/6 23:40
     */
    @RequestMapping(value = "userlogin",method = RequestMethod.POST)
    public User login(@RequestBody User user) {
        try {
            User login = userService.login(user);
            if(login == null){
                throw new Exception();
            }
            return login;
        }catch (Exception e){
            User user1 = new User();
            user1.setUserName("看啥看，说的就是你，小兔崽子不输入用户名密码就想登录！！！");
            user1.setUserPwd("还看，赶紧去登录！！！");
            return user1;
        }
    }
    /**
     * @name  图片验证码
     * @Author VULCAN
     * @Date 2020/5/6 23:40
     */
    @RequestMapping("/getImg_validate")
    public void yanzheng(HttpServletResponse response){

        try {
            ImageUtil.createcode();
            redisTemplate.opsForValue().set("yzm",ImageUtil.createcode(),1, TimeUnit.MINUTES);
            BufferedImage image = ImageUtil.createimage();
//以流的方式返回给客户端
            response.setContentType("image/jpeg");
//response.setContentType("image/bmp");
            ByteArrayOutputStream bt = new ByteArrayOutputStream();
//将图片转换成字节流
            ImageIO.write(image,"jpeg",bt);
//ImageIO.write(image,"bmp",bt);
//得到输出流，返回客户端
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bt.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * @name  邮箱
     * @Author VULCAN
     * @Date 2020/5/6 23:40
     */
    @RequestMapping(value = "/message",method = RequestMethod.POST)
    public String message(@RequestBody User user) throws AddressException, MessagingException {
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");// 连接协议
        properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
        properties.put("mail.smtp.port", 465);// 端口号
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
        properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
        // 得到回话对象
        Session session = Session.getInstance(properties);
        // 获取邮件对象
        Message message = new MimeMessage(session);
        // 设置发件人邮箱地址
        message.setFrom(new InternetAddress("2457422531@qq.com"));
        // 设置收件人邮箱地址
//         message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("2457422531@qq.com"),new InternetAddress("xxx@qq.com"),new InternetAddress("xxx@qq.com")});
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.geteMail()));//一个收件人1992577081
        // 设置邮件标题
        message.setSubject("随机验证码！！！");
        //1.定义变量保存生成后的验证码字符串
         String code = "";
        //2.生成验证码
            String a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";//随机生成的字符范围(0-9,a-z,A-Z)
        //生成验证码的位数(这里是4位)
            for (int i = 0; i < 4; i++) {
                int index = (int) (Math.random() * 62);//会产生一个[0,62)的数，不包含小数
                char b = a.charAt(index);
                code = code + b;
            }
        // 设置邮件内容
        message.setText(code);
        // 得到邮差对象
        Transport transport = session.getTransport();
//          连接自己的邮箱账户
        transport.connect("2457422531@qq.com", "vvemgxhjxgokecgd");// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        return code;
    }
    /**
     * @name  注册
     * @Author VULCAN
     * @Date 2020/5/6 23:40
     */
    @RequestMapping(value = "zhuces",method = RequestMethod.POST)
    public void zhuce(@RequestBody User user) {
        userService.zhuce(user);
    }
    /**
     * @name  重置
     * @Author VULCAN
     * @Date 2020/5/6 23:40
     */
    @RequestMapping(value = "czs",method = RequestMethod.POST)
    public void cz(@RequestBody User user) {
        userService.cz(user);
    }
    /**
     * 查询单个
     * @param id
     * @return
     */
    @RequestMapping(value = "findById/{id}",method = RequestMethod.GET)
    public User findById(@PathVariable String id){
        return userService.findById(id);
    }
    /**
     * 修改个人信息
     * @param user
     */
    @RequestMapping(value = "userupdate",method = RequestMethod.POST)
    public void userupdate(@RequestBody User user){
        //System.err.println(user.toString());
        userService.userupdate(user);
    } /**
     * 修改个人密码
     * @param user
     */
    @RequestMapping(value = "userupdatepwd",method = RequestMethod.POST)
    public void userupdatepwd(@RequestBody User user){
        //System.err.println(user.toString());
        User user1 = userService.findById(user.getUserId());
        user1.setUserPwd(user.getUserPwd());
        userService.userupdate(user1);
    }
    @RequestMapping(value = "yzm",method = RequestMethod.GET)
    public String yzm(){
        String yzm = (String) redisTemplate.opsForValue().get("yzm");
        return yzm;
    }
}
